﻿using System;
using System.Globalization;
using BuzzX8.Xmpp.Properties;

namespace BuzzX8.Xmpp.Connectivity
{
    public class ConnectionSettings
    {
        public static readonly int DefaultClientPort = 5222;
        public static readonly int DefaultServerPort = 5269;

        private FeaturesSettings featuresSettings;
        private bool isReadOnly;
        private string domain;
        private int port;

        public ConnectionSettings() : this(null)
        {
        }

        public ConnectionSettings(ConnectionSettings original) : this(original, false)
        {
        }

        public ConnectionSettings(ConnectionSettings original, bool isReadOnly)
        {
            DefaultCulture = CultureInfo.CurrentCulture;
            featuresSettings = new FeaturesSettings();
            this.isReadOnly = isReadOnly;
            if (original != null) Initialize(original);
        }

        private void Initialize(ConnectionSettings original)
        {
            Domain = original.Domain;
            Port = original.Port;
        }

        public bool IsReadonly
        {
            get { return isReadOnly; }
        }

        public FeaturesSettings FeaturesSettings
        {
            get { return featuresSettings; }
        }

        public CultureInfo DefaultCulture { get; set; }

        public string UserName { get; set; }

        public string Domain
        {
            get { return domain; }
            set
            {
                ThrowExceptionIfReadonly();
                domain = value;
            }
        }

        public string Resource { get; set; }

        public int Port
        {
            get { return port; }
            set
            {
                ThrowExceptionIfReadonly();
                ValidatePortRange(value);
                port = value;
            }
        }

        private void ValidatePortRange(int port)
        {
            if (port < 0) throw new ArgumentOutOfRangeException();
        }

        private void ThrowExceptionIfReadonly()
        {
            if (isReadOnly) throw new InvalidOperationException(Resources.ConnectionSettingsReadonlyExceptionMessage);
        }
    }
}
